package com.sogo;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.util.Log;

public class ServerConnection extends Activity {
	final int TIMEOUT_MILLISEC =30000; //30secs
	public static String encryptPassword(String plaintext)
	{
		MessageDigest m = null;
		try {
			m = MessageDigest.getInstance("MD5");
		} catch (NoSuchAlgorithmException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		m.reset();
		m.update(plaintext.getBytes());
		byte[] digest = m.digest();
		BigInteger bigInt = new BigInteger(1,digest);
		String hashtext = bigInt.toString(16);
		// Now we need to zero pad it if you actually want the full 32 chars.
		while(hashtext.length() < 32 ){
		  hashtext = "0"+hashtext;
		}
		return hashtext;
	}

    public static String convertStreamToString(InputStream is) {
		/*
		* To convert the InputStream to String we use the BufferedReader.readLine()
		* method. We iterate until the BufferedReader return null which means
		* there's no more data to read. Each line will appended to a StringBuilder
		* and returned as String.
		*/
    	BufferedReader reader = new BufferedReader(new InputStreamReader(is));
		StringBuilder sb = new StringBuilder();
		
		String line = null;
		try {
			while ((line = reader.readLine()) != null) {
				sb.append(line + "\n");
			}
		}catch (IOException e) {
			e.printStackTrace();
		}finally{
			try {
				is.close();
			}catch (IOException e) {
				e.printStackTrace();
			}
		}
		return sb.toString();
	}
    
    /*
     * Login function sends user name and password to server to check. If the user information is correct it will return
     * the users information, but when it is incorrect, it will return a NULL.
     * Corresponding Int Values:
     * 0 - Login 
     * 1 - Registration
     * 2 - Search Friends
     * 3 - Adding Friends
     * 4 - Update Location
     * 5 - Get friends coordinates
     * 6 - Get friends list
     * 7 - Delete Friend
     * 8 - Friend Requests
     * 9 - Create Events
     */
	public static JSONArray CommunicateWithServer(JSONObject json, int reason) 
	{
		final int TIMEOUT_MILLISEC =30000; //30secs
		JSONArray jsonArray =null;
	    try {

	        HttpParams httpParams = new BasicHttpParams();
	        HttpConnectionParams.setConnectionTimeout(httpParams,TIMEOUT_MILLISEC);
	        HttpConnectionParams.setSoTimeout(httpParams, TIMEOUT_MILLISEC);
	        HttpClient client = new DefaultHttpClient(httpParams);
	        String url = null;
	        switch(reason)
	        {
	        	case 0: url = "http://www.suopensim.com/app/login.php";
	        		break;
	        	case 1: url = "http://www.suopensim.com/app/register.php";
	        		break;
	        	case 2: url = "http://www.suopensim.com/app/searchForFriends.php";
	        		break;
	        	case 3: url = "http://www.suopensim.com/app/addfriend.php";
	        		break;
	        	case 4: url = "http://www.suopensim.com/app/updateLocation.php";
	        		break;
	        	case 5: url = "http://www.suopensim.com/app/getfriendcords.php";
	        		break;
	        	case 6: url = "http://www.suopensim.com/app/getfriends.php";
	        		break;
	        	case 7: url = "http://www.suopensim.com/app/deleteFriend.php";
	        		break;
	        	case 8: url= "http://www.suopensim.com/app/requests.php";
	        		break;
	        	case 9: url= "http://www.suopensim.com/app/createevent.php";
        			break;
	        	case 10: url= "http://www.suopensim.com/app/getEvents.php";
    				break;
	        	case 11: url= "http://www.suopensim.com/app/addtoevent.php";
    				break;
	        }
	        HttpPost request = new HttpPost(url);
	        request.setEntity(new ByteArrayEntity(json.toString().getBytes(
	                "UTF8")));
	        request.setHeader("json", json.toString());
	        HttpResponse response = client.execute(request);
	        HttpEntity entity = response.getEntity();
	        // If the response does not enclose an entity, there is no need
	        if (entity != null) {
	            InputStream instream = entity.getContent();
	            String result = convertStreamToString(instream);
	            try{
	            	jsonArray = new JSONArray(result);
	            	//return jsonArray;
	            }
	            catch(Throwable t){
	            	jsonArray=null;
	            	//jsonArray;
	            }
	            
	        }
	    } catch (Throwable t) {
			Log.e(ServerConnection.class.getName(), "Request failed: " + t.toString());
	    }
		
		return jsonArray;
	}
	/*This metho returns a json object*/
	public static JSONObject testingnewfunction(){

		//initialize
		InputStream is = null;
		String result = "";
		JSONObject jArray = null;
		String url = "http://api.geonames.org/postalCodeSearchJSON?formatted=true&postalcode=9791&maxRows=10&username=demo&style=full";
		//http post
		try{
			HttpClient httpclient = new DefaultHttpClient();
			HttpPost httppost = new HttpPost(url);
			HttpResponse response = httpclient.execute(httppost);
			HttpEntity entity = response.getEntity();
			is = entity.getContent();

		}catch(Exception e){
			Log.e("log_tag", "Error in http connection "+e.toString());
		}

		//convert response to string
		try{
			BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
			StringBuilder sb = new StringBuilder();
			String line = null;
			while ((line = reader.readLine()) != null) {
				sb.append(line + "\n");
			}
			is.close();
			result=sb.toString();
		}catch(Exception e){
			Log.e("log_tag", "Error converting result "+e.toString());
		}

		//try parse the string to a JSON object
		try{
	        	jArray = new JSONObject(result);
		}catch(JSONException e){
			Log.e("log_tag", "Error parsing data "+e.toString());
		}

		return jArray;
	}
}
